import random
import re

from celery import current_app
from flask import Blueprint, make_response, request, session, jsonify

from models import User, db
from response_code import RET
from utils.captcha.captcha import captcha


"""
请求路径:前缀/yzm
请求方式: GET
请求参数:手机号码,短信验证,密码
返回值:状态
"""
user_blueprint = Blueprint("user", __name__)
# 创建蓝图认证对象


@user_blueprint.route('/yzm')
def Yanzm():
    # 图片验证码
    name, text, image = captcha.generate_captcha()
    print(text)
    session['image_yzm'] = text
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpeg'
    return response


@user_blueprint.route('/send_sms')
def sms():
    # 短信验证码
    # 1 接收请求参数
    data = request.args
    imageCode = data.get("imageCode")
    mobile = data.get("mobile")

    # 2 验证参数是否存在
    if not all([imageCode, mobile]):
        return jsonify(code=RET.PARAMERR, msg="参数不全")
    # 3 验证手机号格式
    if not re.match(r"^1[3-9]\d{9}",mobile):
        return jsonify(code=RET.DATAERR, msg="手机格式不正确")
    # 3 验证手机号是否注册
    if User.query.filter_by(phone=mobile).count():
        return jsonify(code=RET.PARAMERR, msg="该用户已存在")
    # 3 验证图片验证码
    if imageCode.lower() != session['image_yzm'].lower():
        return jsonify(code=RET.PARAMERR, msg="验证码错误")
    # 3 生成短信验证码.并保存到session
    sms_code = "%05d" % random.randint(0, 99999)
    session['sms_yzm'] = sms_code
    session['mobile'] = mobile
    print(sms_code)
    return jsonify(code=RET.OK, mdg='发送成功')


@user_blueprint.route('/user_register', methods=['POST'])
def user_register():
    # 注册功能
    # 接收参数
    dcit_data = request.form   # 获取表单数据
    mobile1 = dcit_data.get('mobile')
    imagecode = dcit_data.get('imagecode')
    phonecode = dcit_data.get('phonecode')
    password1 = dcit_data.get('password')
    password2 = dcit_data.get('password2')

    # 判空效验
    if not all([mobile1, imagecode, phonecode, password1, password2]):
        return jsonify(code=RET.DATAERR, msg="参数不全")
    # 效验短信验证
    if phonecode != session['sms_yzm']:
        return jsonify(code=RET.DATAERR, msg="验证码错误")
    # 效验手机号
    if mobile1 != session['mobile']:
        return jsonify(code=RET.DATAERR, msg="手机号码有误")
    # 效验是否已经注册
    if User.query.filter_by(phone=mobile1).count():
        return jsonify(code=RET.DATAERR, msg="该用户已存在")
    # 效验密码是否一致
    if password2 != password1:
        return jsonify(code=RET.DATAERR, msg="密码不一致")

    # 创建注册用户对象
    user = User()
    user.phone = mobile1
    user.name = mobile1
    user.password = password1

    # 存入用户对象到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="注册失败")

    return jsonify(code=RET.OK, msg="注册成功")
